package com.sha.mumbailocal.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;
import java.util.HashMap;
import java.util.Map;

public class BeanPropertyUtil {

	private static Map<Class<?>, PropertyEditor> editorMap = null;

	public static Map<String, PropertyDescriptor> loadDescriptorMap(Class cls)
			throws IntrospectionException {
		Map<String, PropertyDescriptor> map = new HashMap<String, PropertyDescriptor>();

		PropertyDescriptor[] descriptors;
		descriptors = loadDescriptors(cls);
		for (PropertyDescriptor descriptor : descriptors) {
			map.put(descriptor.getName().trim(), descriptor);
		}

		return map;
	}

	private static PropertyDescriptor[] loadDescriptors(Class cls)
			throws IntrospectionException {
		BeanInfo beanInfo = Introspector.getBeanInfo(cls);
		return beanInfo.getPropertyDescriptors();
	}

	private static PropertyEditor getPropertyEditorValue(Class<?> cls) {
		if (editorMap == null) {
			editorMap = new HashMap<Class<?>, PropertyEditor>();
		}

		PropertyEditor editor = editorMap.get(cls);

		if (editor == null) {
			editor = PropertyEditorManager.findEditor(cls);
			addEditorToMap(cls, editor);
		}

		return editor;
	}

	private static PropertyEditor getPropertyEditor(PropertyDescriptor desc)
			throws InstantiationException, IllegalAccessException {
		Class<?> cls = desc.getPropertyEditorClass();
		if (null != cls)
			return (PropertyEditor) cls.newInstance();
		return getPropertyEditorValue(desc.getPropertyType());
	}

	public static Object convertValue(String value, PropertyDescriptor prop)
			throws InstantiationException, IllegalAccessException {
		PropertyEditor editor = getPropertyEditor(prop);
		Object obj = value;
		if (null != editor) {
			editor.setAsText(value);
			obj = editor.getValue();
		}
		return obj;
	}

	public static void addEditorToMap(Class<?> cls, PropertyEditor editor) {
		if (editor != null) {
			editorMap.put(cls, editor);
		}
	}
}
